const Application = require("../models/Application");

exports.getApplication = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 3
  try {
    let total = await Application.find().count()
    let result = await Application.find().sort({'date': -1}).select("_id name phone resource isDispose date").skip((pageNumber - 1) * pageSize).limit(pageSize)
    result = result.map(item => {
      return {
        _id: item._id,
        name: item.name,
        phone:item.phone,
        resource:item.resource,
        isDispose:item.isDispose,
        date: item.date
      }
    })
    res.json({
      code: 20000,
      data: result,
      pagination: {
        total,
        pageSize,
        pageNumber
      }
    })
  } catch (err) {
    next(err)
  }
}


exports.postApplication = async (req, res, next) => {
  try {
    const model = await Application.create(req.body)
    res.send({
      code: 20000,
      message: '申请提交成功!'
    })
  } catch (err) {
    console.log(err)
    next(err)
  }

}

exports.isDispose = async (req, res, next) => {
  const _id = req.body.id
  const isDispose = req.body.isDispose
  var json = {isDispose: isDispose, date: Date.now()}
  try {
    await Application.findByIdAndUpdate(_id, json)
    res.json({
      code: 20000,
      message: '更新状态成功'
    })
  } catch (err) {
    next(err)
  }
}
